package daily_task

import (
	"go_server/game_server/api/service/bag"
	"go_server/game_server/dao/daily_dao"
	"go_server/game_server/dataconfig/config_manager"
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/game_server/world_manager"
	"go_server/zinx/ziface"
	"go_server/zinx/znet"
	"gorm.io/datatypes"
	"time"
)

type GetDailyTaskPrizeApi struct {
	znet.BaseRouter
}

// 领取任务奖励
func (*GetDailyTaskPrizeApi) Handle(request ziface.IRequest) {
	msg := &pb.GetDailyTaskPrizeC2S{}
	if !util.PBParseRet(request, msg) {
		return
	}

	conn := request.GetConnection()
	roleId := ServiceObj.GetRoleId(request)

	taskConfig, ok := config_manager.GetStcTableTask_SheetTaskById(msg.TaskId)
	if !ok {
		world_manager.WorldMgrObj.SendClientErrMsg(roleId, request, pb.ErrorCodeManager_DAILY_TASK_UNFIND, nil)
		return
	}

	dateKey := time.Now().Format("20060102") // 格式化日期
	fields := []string{"daily_task", "active"}
	row := daily_dao.GetDailyByDateKey(dateKey, roleId, fields) // 获取当前每日任务进度

	var active int32                            // 当日活跃度
	taskIdToProgress := make(map[int32][]int32) // 当日任务进度

	if row != nil {
		active = row.Active

		if row.DailyTask.Data() != nil {
			taskIdToProgress = row.DailyTask.Data()
		}
	}

	// 根据任务ID从玩家任务进度中获取任务信息
	taskInfo, exist := taskIdToProgress[msg.TaskId]
	if !exist || taskInfo[2] != 1 {
		world_manager.WorldMgrObj.SendClientErrMsg(roleId, request, pb.ErrorCodeManager_TASK_UNCOMPLETE, nil)
		return
	}

	taskIdToProgress[msg.TaskId][2] = 2 // 任务状态改为已领取
	active += taskConfig.ActivityReward // 增加活跃值

	res := &pb.GetMainTaskPrizeS2C{
		TaskId: msg.TaskId,
		State:  taskIdToProgress[msg.TaskId][2],
	}

	// 优先返回下行
	conn.SendBuffPBMsg(uint32(pb.ProtocolManager_GetDailyTaskPrize), res)

	// 修改任务状态
	dailyObj := daily_dao.Daily{
		DateKey:   dateKey,
		RoleId:    roleId,
		Active:    active,
		DailyTask: datatypes.NewJSONType(taskIdToProgress),
	}
	daily_dao.UpdateDailyByDateKey(&dailyObj, fields)

	// 推送每日任务列表下行
	msgS2C := ServiceObj.GetDailyTaskList.GetDailyTaskListApiS2C(roleId)
	conn.SendBuffPBMsg(uint32(pb.ProtocolManager_GetDailyTaskList), msgS2C)

	// 发送奖励
	bag.AddItemArrayInt32(roleId, taskConfig.TaskReward)
}
